package com.ss.android.article.browser.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewParent;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;

import com.a.a.NightMode;
import com.a.a.t;
import com.a.a.u;
import com.bytedance.common.utility.UIUtils;
import com.ss.android.article.browser.FeedFragment;
import com.ss.android.article.browser.WebViewClientDelegate;
import com.ss.android.article.browser.c.SpecialPageHelper;
import com.ss.android.article.browser.dialog.LightningDialogBuilder;
import com.ss.android.article.browser.preference.PreferenceManager;
import com.ss.android.newmedia.webview.SSWebView;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Map;

import inline.ResourcesDemo;

public final class Browser {
    final class b implements View.OnTouchListener {
        private final Browser d;
        private float a;
        private float b;
        private int c;

        b(Browser arg1, byte arg2) {
            this(arg1);
        }

        private b(Browser arg1) {
            this.d = arg1;

        }

        @SuppressLint(value = {"ClickableViewAccessibility"})
        public final boolean onTouch(@Nullable View arg5, @NonNull MotionEvent arg6) {
            if (arg5 != null) {
                if (!arg5.hasFocus()) {
                    arg5.requestFocus();
                }

                this.c = arg6.getAction();
                this.b = arg6.getY();
                if (this.c == 0) {
                    this.a = this.b;
                } else if (this.c == 1) {
                    float v0 = this.b - this.a;
                    if (v0 > (((float) Browser.h)) && arg5.getScrollY() < Browser.h) {
//                        this.d.m;
                    } else if (v0 < (((float) (-Browser.h)))) {
//                        this.d.m;
                    }

                    this.a = 0f;
                }

                mGestureDetector.onTouchEvent(arg6);
            }

            return false;
        }
    }

    final class BrowserHandler extends Handler {
        @NonNull
        private final WeakReference<Browser> mRefBrowser;

        BrowserHandler(@NonNull Browser arg2) {
            this.mRefBrowser = new WeakReference(arg2);
        }

        public final void handleMessage(@NonNull Message message) {
            super.handleMessage(message);
            String url = message.getData().getString("url");
            Browser browser = this.mRefBrowser.get();
            if (browser != null) {
                browser.a(url);
            }
        }
    }

    @NonNull
    public final r a;
    final boolean b;
    @NonNull
    final Map mAdditionalHttpHeaders;
    PreferenceManager mPreferenceManager;
    @Nullable
    public SSWebView mSSWebView;
    boolean isHardwareAccelerateEnabled;
    private static final int SDK_INT = Build.VERSION.SDK_INT;
    private static final int h = ResourcesDemo.dp2px(10f);
    private static final float[] i = new float[]{-1f, 0f, 0f, 0f, 255f, 0f, -1f, 0f, 0f, 255f, 0f, 0f, -1f, 0f, 255f, 0f, 0f, 0f, 1f, 0f};
    private static final float[] j = new float[]{2f, 0f, 0f, 0f, -160f, 0f, 2f, 0f, 0f, -160f, 0f, 0f, 2f, 0f, -160f, 0f, 0f, 0f, 1f, 0f};
    @Nullable
    private static String sUserAgentString;
    private static float scaledMaximumFlingVelocity;
    @NonNull
    private final WebViewClientDelegate m;
    @NonNull
    private final GestureDetector mGestureDetector;
    @NonNull
    private final Activity mActivity;
    @NonNull
    private final Paint mPaint;
    @NonNull
    private final BrowserHandler q;
    private final BrowserWebChromeClient mBrowserWebChromeClient;
    private final BrowserWebViewClient mBrowserWebViewClient;
    private LightningDialogBuilder mLightningDialogBuilder;
    private BroadcastReceiver mBroadcastReceiver;

    @SuppressLint({"NewApi", "WrongConstant"})
    public Browser(@NonNull Activity activity, FeedFragment feedFragment, boolean arg12) {
        int v8 = 16;
        int v7 = 2;
        int v6 = -1;

        this.mPaint = new Paint();
        this.q = new BrowserHandler(this);
        this.mAdditionalHttpHeaders = new ArrayMap();
        this.isHardwareAccelerateEnabled = false;
        this.mBroadcastReceiver = new com.ss.android.article.browser.view.b(this);
        this.mPreferenceManager = PreferenceManager.getInstance();
        this.mLightningDialogBuilder = LightningDialogBuilder.a();
        com.ss.android.article.browser.c.f.a();
        this.mActivity = activity;
        this.m = feedFragment;
        this.mSSWebView = new SSWebView(activity);
        this.mSSWebView.setId(ViewIdGenerator.generate());
        this.b = arg12;
        this.a = new r(activity);
        Browser.scaledMaximumFlingVelocity = ((float) ViewConfiguration.get(activity).getScaledMaximumFlingVelocity());
        this.mSSWebView.setDrawingCacheBackgroundColor(v6);
        this.mSSWebView.setFocusableInTouchMode(true);
        this.mSSWebView.setFocusable(true);
        this.mSSWebView.setDrawingCacheEnabled(false);
        this.mSSWebView.setWillNotCacheDrawing(true);
        if (Build.VERSION.SDK_INT <= 22) {
            this.mSSWebView.setAnimationCacheEnabled(false);
            this.mSSWebView.setAlwaysDrawnWithCacheEnabled(false);
        }

        this.mSSWebView.setBackgroundColor(v6);
        this.mSSWebView.setScrollbarFadingEnabled(true);
        this.mSSWebView.setSaveEnabled(true);
        this.mSSWebView.setNetworkAvailable(true);
        this.mBrowserWebChromeClient = new BrowserWebChromeClient(activity, feedFragment, this);
        this.mBrowserWebViewClient = new BrowserWebViewClient(activity, feedFragment, this);
        this.mSSWebView.setWebChromeClient(this.mBrowserWebChromeClient);
        this.mSSWebView.setWebViewClient(this.mBrowserWebViewClient);
        this.mSSWebView.setDownloadListener(new com.ss.android.article.browser.download.a.b(activity));
        this.mGestureDetector = new GestureDetector(activity, new GestureDetector.SimpleOnGestureListener() {
            private boolean a = true;

            public final boolean onDoubleTapEvent(MotionEvent motionEvent) {
                this.a = false;
                return false;
            }

            public final boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                int v0 = (int) (100f * velocityY / scaledMaximumFlingVelocity);
                if (v0 < -10) {
//                    Browser.this.m;
                } else if (v0 > 15) {
//                   Browser.this.m;
                }

                return super.onFling(e1, e2, velocityX, velocityY);
            }

            public final void onLongPress(MotionEvent motionEvent) {
                if (this.a) {
                    Message message = Browser.this.q.obtainMessage();
                    if (message != null) {
                        message.setTarget(Browser.this.q);
                        if (mSSWebView != null) {
                            mSSWebView.requestFocusNodeHref(message);
                        }
                    }
                }
            }

            public final void onShowPress(MotionEvent arg2) {
                this.a = true;
            }
        });
        this.mSSWebView.setOnTouchListener(new b(this, (byte) 0));
        Browser.sUserAgentString = this.mSSWebView.getSettings().getUserAgentString();
        if (this.mSSWebView != null) {
            final WebSettings settings = this.mSSWebView.getSettings();
            if (Browser.SDK_INT < 18) {
                settings.setAppCacheMaxSize(9223372036854775807L);
            }

            if (Browser.SDK_INT < 17) {
                settings.setEnableSmoothTransition(true);
            }

            if (Browser.SDK_INT > v8) {
                settings.setMediaPlaybackRequiresUserGesture(true);
            }

            if (Browser.SDK_INT >= 21 && !this.b) {
                settings.setMixedContentMode(v7);
            } else if (Browser.SDK_INT >= 21) {
                settings.setMixedContentMode(1);
            }

            if (!this.b) {
                settings.setDomStorageEnabled(true);
                settings.setAppCacheEnabled(true);
                settings.setCacheMode(v6);
                settings.setDatabaseEnabled(true);
            } else {
                settings.setDomStorageEnabled(false);
                settings.setAppCacheEnabled(false);
                settings.setDatabaseEnabled(false);
                settings.setCacheMode(v7);
            }

            settings.setSupportZoom(true);
            settings.setBuiltInZoomControls(true);
            settings.setDisplayZoomControls(false);
            settings.setAllowContentAccess(true);
            settings.setAllowFileAccess(true);
            if (Browser.SDK_INT >= v8) {
                settings.setAllowFileAccessFromFileURLs(false);
                settings.setAllowUniversalAccessFromFileURLs(false);
            }

            com.a.a.s v1 = this.b("appcache");
            v1.b = android.support.design.a.c();
            v1.c = android.support.design.a.b();
            v1.a(new com.ss.android.article.browser.view.c(settings));
            if (Build.VERSION.SDK_INT <= 23) {
                v1 = this.b("geolocation");
                v1.b = android.support.design.a.c();
                v1.c = android.support.design.a.b();
                v1.a(new d(settings));
            }

            v1 = this.b("databases");
            v1.b = android.support.design.a.c();
            v1.c = android.support.design.a.b();
            v1.a(new t() {

                public final void a() {
                }

                public final void a(@Nullable Object arg3) {
                    if (Browser.SDK_INT < 19) {
                        settings.setDatabasePath(((File) arg3).getPath());
                    }
                }
            });
        }

        this.a(activity);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.ss.android.article.browser.modifyFontSize");
        LocalBroadcastManager.getInstance(activity).registerReceiver(this.mBroadcastReceiver, intentFilter);
    }

    public synchronized final void loadUrl(@NonNull String url) {
        synchronized (this) {
            SpecialPageHelper.isHomePageUrl(url);
            if (this.mSSWebView != null) {
                Log.d("Browser", "load url : " + url);
                this.mSSWebView.loadUrl(url, this.mAdditionalHttpHeaders);
            }
        }
    }

    public final void setWebViewVisibility(int visibility) {
        if (this.mSSWebView != null) {
            ViewParent viewParent = this.mSSWebView.getParent();
            if ((viewParent instanceof View)) {
                UIUtils.setVisibility(((View) viewParent), visibility);
            }
        }
    }

    public final boolean isWebViewVisible() {
        if (mSSWebView != null) {
            ViewParent viewParent = mSSWebView.getParent();
            if (!(viewParent instanceof View)) {
                return mSSWebView != null && mSSWebView.isShown();
            } else {
                return ((View) viewParent).getVisibility() == View.VISIBLE;
            }
        } else {
            return mSSWebView != null && mSSWebView.isShown();
        }
    }

    public final void a(TextView arg2) {
        this.a.tv = arg2;
    }

    @SuppressLint(value = {"NewApi", "SetJavaScriptEnabled"})
    private void a(@NonNull Context context) {
        int v8 = 19;
        int v7 = 18;
        synchronized (this) {
            if (this.mSSWebView == null) {
                return;
            }

            WebSettings webViewSettings = this.mSSWebView.getSettings();
            if (this.mPreferenceManager.mSharedPreferences.getBoolean("doNotTrack", false)) {
                this.mAdditionalHttpHeaders.put("DNT", "1");
            } else {
                this.mAdditionalHttpHeaders.remove("DNT");
            }

            if (this.mPreferenceManager.mSharedPreferences.getBoolean("removeIdentifyingHeaders", false)) {
                this.mAdditionalHttpHeaders.put("X-Requested-With", "");
                this.mAdditionalHttpHeaders.put("X-Wap-Profile", "");
            } else {
                this.mAdditionalHttpHeaders.remove("X-Requested-With");
                this.mAdditionalHttpHeaders.remove("X-Wap-Profile");
            }

            webViewSettings.setDefaultTextEncodingName(this.mPreferenceManager.mSharedPreferences.getString("textEncoding", "UTF-8"));
            this.mPreferenceManager.mSharedPreferences.getString("home", "about:home");
            int renderMode = this.mPreferenceManager.mSharedPreferences.getInt("renderMode", 0);
            this.isHardwareAccelerateEnabled = false;
            ColorMatrix v2_1;
            switch (renderMode) {
                case 0: {
                    this.mPaint.setColorFilter(null);
                    if (this.mSSWebView != null) {
                        this.mSSWebView.setLayerType(View.LAYER_TYPE_NONE, null);
                    }
                    this.isHardwareAccelerateEnabled = false;
                    break;
                }
                case 1: {
                    this.mPaint.setColorFilter(new ColorMatrixColorFilter(Browser.i));
                    this.enableHardwareAccelerate();
                    this.isHardwareAccelerateEnabled = true;
                    break;
                }
                case 2: {
                    v2_1 = new ColorMatrix();
                    v2_1.setSaturation(0f);
                    this.mPaint.setColorFilter(new ColorMatrixColorFilter(v2_1));
                    this.enableHardwareAccelerate();
                    break;
                }
                case 3: {
                    v2_1 = new ColorMatrix();
                    v2_1.set(Browser.i);
                    ColorMatrix v4 = new ColorMatrix();
                    v4.setSaturation(0f);
                    ColorMatrix v5 = new ColorMatrix();
                    v5.setConcat(v2_1, v4);
                    this.mPaint.setColorFilter(new ColorMatrixColorFilter(v5));
                    this.enableHardwareAccelerate();
                    this.isHardwareAccelerateEnabled = true;
                    break;
                }
                case 4: {
                    this.mPaint.setColorFilter(new ColorMatrixColorFilter(Browser.j));
                    this.enableHardwareAccelerate();
                    break;
                }
            }

            if (this.b) {
                webViewSettings.setGeolocationEnabled(false);
            } else {
                webViewSettings.setGeolocationEnabled(this.mPreferenceManager.mSharedPreferences.getBoolean("location", false));
            }

            if (Browser.SDK_INT < v8) {
                switch (this.mPreferenceManager.mSharedPreferences.getInt("enableflash", 0)) {
                    case 0: {
                        webViewSettings.setPluginState(WebSettings.PluginState.OFF);
                        break;
                    }
                    case 1: {
                        webViewSettings.setPluginState(WebSettings.PluginState.ON_DEMAND);
                        break;
                    }
                    case 2: {
                        webViewSettings.setPluginState(WebSettings.PluginState.ON);
                        break;
                    }
                }
            }

            int agentchoose = this.mPreferenceManager.mSharedPreferences.getInt("agentchoose", 1);
            if (this.mSSWebView != null) {
                WebSettings webSettings = this.mSSWebView.getSettings();
                switch (agentchoose) {
                    case 1: {
                        if (Browser.SDK_INT >= 17) {
                            webSettings.setUserAgentString(WebSettings.getDefaultUserAgent(context));
                        } else {
                            webSettings.setUserAgentString(Browser.sUserAgentString);
                        }
                        break;
                    }
                    case 2: {
                        webSettings.setUserAgentString("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36");
                        break;
                    }
                    case 3: {
                        webSettings.setUserAgentString("Mozilla/5.0 (Linux; U; Android 4.4; en-us; Nexus 4 Build/JOP24G) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
                        break;
                    }
                    case 4: {
                        String userAgentString = this.mPreferenceManager.mSharedPreferences.getString("userAgentString", Browser.sUserAgentString);
                        if (userAgentString == null || (userAgentString.isEmpty())) {
                            userAgentString = " ";
                        }
                        webSettings.setUserAgentString(userAgentString);
                        break;
                    }
                }

            }

            if (!this.mPreferenceManager.mSharedPreferences.getBoolean("passwords", true) || (this.b)) {
                if (Browser.SDK_INT < v7) {
                    webViewSettings.setSavePassword(false);
                }

                webViewSettings.setSaveFormData(false);
            } else {
                if (Browser.SDK_INT < v7) {
                    webViewSettings.setSavePassword(true);
                }

                webViewSettings.setSaveFormData(true);
            }

            if (this.mPreferenceManager.mSharedPreferences.getBoolean("java", true)) {
                webViewSettings.setJavaScriptEnabled(true);
                webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
            } else {
                webViewSettings.setJavaScriptEnabled(false);
                webViewSettings.setJavaScriptCanOpenWindowsAutomatically(false);
            }

            if (!this.mPreferenceManager.getTextReflow()) {
                webViewSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
            } else {
                webViewSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
                if (Browser.SDK_INT < v8) {
                } else {
                    try {
                        webViewSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
                    } catch (Exception exception) {
                        Log.e("Browser", "Problem setting LayoutAlgorithm to TEXT_AUTOSIZING");
                    }
                }
            }
            try {
                webViewSettings.setBlockNetworkImage(this.mPreferenceManager.mSharedPreferences.getBoolean("blockimages", false));
                if (this.b) {
                    webViewSettings.setSupportMultipleWindows(false);
                } else {
                    webViewSettings.setSupportMultipleWindows(this.mPreferenceManager.mSharedPreferences.getBoolean("newwindows", false));
                }

                webViewSettings.setUseWideViewPort(this.mPreferenceManager.mSharedPreferences.getBoolean("wideviewport", true));
                webViewSettings.setLoadWithOverviewMode(this.mPreferenceManager.mSharedPreferences.getBoolean("overviewmode", true));
                switch (this.mPreferenceManager.getTextSize()) {
                    case 0: {
                        webViewSettings.setTextZoom(50);
                        break;
                    }
                    case 1: {
                        webViewSettings.setTextZoom(100);
                        break;
                    }
                    case 2: {
                        webViewSettings.setTextZoom(200);
                        break;
                    }
                }

                if (Build.VERSION.SDK_INT >= 21) {
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptThirdPartyCookies(mSSWebView, !this.mPreferenceManager.mSharedPreferences.getBoolean("thirdParty", false));
                }
            } catch (Throwable v0_1) {
            }
        }
    }

    static Activity a(Browser arg1) {
        return arg1.mActivity;
    }

    void a(String url) {
        Activity v0_1;
        int v4 = 8;
        int v3 = 5;
        if (mSSWebView != null) {
            WebView.HitTestResult hitTestResult = mSSWebView.getHitTestResult();
            String currentUrl = mSSWebView.getUrl();
            if (currentUrl != null && (SpecialPageHelper.isSpecialUrl(currentUrl))) {
                if (SpecialPageHelper.isHistoryUrl(currentUrl)) {
                    if (url != null) {
                        mLightningDialogBuilder.a(mActivity, url);
                    } else if (hitTestResult == null && hitTestResult.getExtra() != null) {
                        mLightningDialogBuilder.a(mActivity, hitTestResult.getExtra());
                    }
                } else if (SpecialPageHelper.isBookmarksUrl(currentUrl)) {
                    if (url != null) {
                        mLightningDialogBuilder.a(mActivity, m, url);
                    } else if (hitTestResult == null && hitTestResult.getExtra() != null) {
                        mLightningDialogBuilder.a(mActivity, m, hitTestResult.getExtra());
                    }
                } else if (SpecialPageHelper.isDownloadsUrl(currentUrl)) {
                    if (url != null) {
                        mLightningDialogBuilder.a(mActivity);
                    } else if (hitTestResult == null && hitTestResult.getExtra() != null) {
                        hitTestResult.getExtra();
                        mLightningDialogBuilder.a(mActivity);
                    }
                }

                return;
            }

            if (url != null) {
                if (hitTestResult != null) {
                    if (hitTestResult.getType() != v4 && hitTestResult.getType() != v3) {
                        LightningDialogBuilder.c(mActivity, url);
                        return;
                    }

                    v0_1 = mActivity;
                    getUserAgent();
                    LightningDialogBuilder.b(v0_1, url);
                    return;
                }

                LightningDialogBuilder.c(mActivity, url);
                return;
            }

            if (hitTestResult == null) {
                return;
            }

            if (hitTestResult.getExtra() == null) {
                return;
            }

            currentUrl = hitTestResult.getExtra();
            if (hitTestResult.getType() != v4 && hitTestResult.getType() != v3) {
                LightningDialogBuilder.c(mActivity, currentUrl);
                return;
            }

            v0_1 = mActivity;
            getUserAgent();
            LightningDialogBuilder.b(v0_1, currentUrl);
        }
    }

    public final void onResume() {
        synchronized (this) {
            if (this.mSSWebView != null) {
                this.mSSWebView.onResume();
                Log.d("Browser", "WebView resume: " + this.mSSWebView.getId());
            }
        }
    }

    @NonNull
    private com.a.a.s b(final String arg2) {
        return com.a.a.s.a(new NightMode() {

            public final void f(@NonNull Object arg4) {
                ((u) arg4).onItem(Browser.a(Browser.this).getDir(arg2, 0));
                ((u) arg4).onComplete();
            }
        });
    }

    static WebViewClientDelegate b(Browser arg1) {
        return arg1.m;
    }

    public final void c() {
        synchronized (this) {
            if (this.mSSWebView != null) {
                this.mSSWebView.stopLoading();
            }
            this.mBrowserWebChromeClient.onProgressChanged(this.mSSWebView, 100);
        }
    }

    public final void pauseJSTimers() {
        synchronized (this) {
            if (this.mSSWebView != null) {
                this.mSSWebView.pauseTimers();
                Log.d("Browser", "Pausing JS timers");
            }
        }
    }

    public final void resumeJSTimers() {
        synchronized (this) {
            if (this.mSSWebView != null) {
                this.mSSWebView.resumeTimers();
                Log.d("Browser", "Resuming JS timers");
            }
        }
    }

    public final void reload() {
        synchronized (this) {
            if (this.mSSWebView != null) {
                this.mSSWebView.reload();
            }
        }
    }

    public final void unregisterReceiver() {
        synchronized (this) {
            LocalBroadcastManager.getInstance(this.mActivity).unregisterReceiver(this.mBroadcastReceiver);
        }
    }

    public final void goBack() {
        synchronized (this) {
            if (this.mSSWebView != null) {
                this.mSSWebView.goBack();
            }
        }
    }

    public final void goForward() {
        synchronized (this) {
            if (this.mSSWebView != null) {
                this.mSSWebView.goForward();
            }
        }
    }

    public final boolean canGoBack() {
        return this.mSSWebView != null && this.mSSWebView.canGoBack();
    }

    public final boolean canGoForward() {
        return this.mSSWebView != null && this.mSSWebView.canGoForward();
    }

    @Nullable
    public final WebView getWebView() {
        SSWebView ssWebView;
        synchronized (this) {
            ssWebView = this.mSSWebView;
        }
        return ((WebView) ssWebView);
    }

    @NonNull
    public final String getUrl() {
        return this.mSSWebView == null || this.mSSWebView.getUrl() == null ? "" : this.mSSWebView.getUrl();
    }

    public final void clearHistory() {
        if (this.mSSWebView != null) {
            this.mSSWebView.clearHistory();
        }
    }

    public final boolean isPageLoading() {
        return this.mBrowserWebViewClient.isPageLoading;
    }

    private void enableHardwareAccelerate() {
        if (this.mSSWebView != null) {
            this.mSSWebView.setLayerType(View.LAYER_TYPE_HARDWARE, this.mPaint);
        }
    }

    @NonNull
    private String getUserAgent() {
        return this.mSSWebView != null ? this.mSSWebView.getSettings().getUserAgentString() : "";
    }
}

